
package com.cyanite.playlv2;

import com.cyanite.playlv2.preferences.Preferences;
import com.cyanite.playlv2.util.NotificationsUtil;
import com.cyanite.playlv2api.PlayLv2Api;
import com.cyanite.playlv2.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Login activity, if account has been saved into preference, it will directly
 * login.
 */
public class LoginActivity extends Activity {

    private EditText mUserName;
    private EditText mPassword;

    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow()
                .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        setContentView(R.layout.login_activity);

        Preferences.logoutUser(((PlayLv2) getApplication()).getPlayLv2Api(), PreferenceManager
                .getDefaultSharedPreferences(this).edit());

        ensureUi();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private ProgressDialog showProgressDialog() {
        if (mProgressDialog == null) {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage(getString(R.string.login_dialog_message));
            dialog.setIndeterminate(true);
            dialog.setCancelable(true);
            mProgressDialog = dialog;
        }
        mProgressDialog.show();
        return mProgressDialog;
    }

    private void dismissProgressDialog() {
        mProgressDialog.dismiss();
    }

    private void ensureUi() {
        final Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                AsyncTask<Void, Void, Boolean> mLoginTask = new LoginTask();
                mLoginTask.execute();
            }
        });

        TextView newAccount = (TextView) findViewById(R.id.newAccountTextView);
        newAccount.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
            }
        });

        mUserName = ((EditText) findViewById(R.id.phoneEditText));
        mPassword = ((EditText) findViewById(R.id.passwordEditText));

        TextWatcher fieldValidatorTextWatcher = new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                button.setEnabled(phoneNumberEditTextFieldIsValid()
                        && passwordEditTextFieldIsValid());
            }

            private boolean phoneNumberEditTextFieldIsValid() {
                // This can be either a phone number or username so we don't
                // care too much about the format.
                return !TextUtils.isEmpty(mUserName.getText());
            }

            private boolean passwordEditTextFieldIsValid() {
                return !TextUtils.isEmpty(mPassword.getText());
            }
        };

        mUserName.addTextChangedListener(fieldValidatorTextWatcher);
        mPassword.addTextChangedListener(fieldValidatorTextWatcher);
    }

    private class LoginTask extends AsyncTask<Void, Void, Boolean> {

        private Exception mReason;

        @Override
        protected void onPreExecute() {
            showProgressDialog();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(LoginActivity.this);
            Editor editor = prefs.edit();
            PlayLv2 playlv2 = (PlayLv2) getApplication();
            boolean loggedIn = false;
            PlayLv2Api playlv2api = playlv2.getPlayLv2Api();
            String phoneNumber = mUserName.getText().toString();
            String password = mPassword.getText().toString();
            try {
                loggedIn = Preferences.loginUser(playlv2api, phoneNumber, password, editor);
            } catch (Exception ex) {
                mReason = ex;
                return false;
            }
            return loggedIn;
        }

        @Override
        protected void onPostExecute(Boolean loggedIn) {
            if (loggedIn) {
                sendBroadcast(new Intent(PlayLv2.INTENT_ACTION_LOGGED_IN));
                Toast.makeText(LoginActivity.this, getString(R.string.login_welcome_toast),
                        Toast.LENGTH_LONG).show();

                // Launch the main activity to let the user do anything.
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();

            } else {
                sendBroadcast(new Intent(PlayLv2.INTENT_ACTION_LOGGED_OUT));
                NotificationsUtil.ToastReasonForFailure(LoginActivity.this, mReason);
            }
            dismissProgressDialog();
        }

        @Override
        protected void onCancelled() {
            dismissProgressDialog();
        }
    }
}
